/**
 * AI智能助理悬浮窗 v2.0
 * 简洁美观版本 - 纯CSS图标设计
 */

;(function (global) {
  'use strict'

  // 默认配置
  const defaultConfig = {
    // 必需参数
    token: null,
    datasetId: null,

    // 外观配置
    position: 'bottom-right', // bottom-right, bottom-left, top-right, top-left
    size: 64, // 助理大小(px)
    offset: { x: 40, y: 40 }, // 距离边缘的偏移量

    // 样式配置
    theme: 'gradient', // gradient(渐变), solid(纯色), outline(轮廓)
    primaryColor: '#667eea',
    secondaryColor: '#764ba2',
    iconType: 'robot', // robot(机器人), chat(对话), ai(AI文字), brain(大脑)

    // 行为配置
    draggable: true,
    showBadge: true,
    autoHide: false,
    autoHideDelay: 5000,

    // 聊天窗口配置
    baseUrl: window.location.origin,
    modalWidth: 1100, // 聊天窗口宽度(px)
    modalHeight: 800, // 聊天窗口高度(px)

    // 回调函数
    onOpen: null,
    onClose: null,
    onReady: null,

    // 文本配置
    tooltip: 'AI智能助理 - 点击开始对话',
  }

  /**
   * AI助理悬浮窗组件类
   */
  class AIAssistantWidget {
    constructor(config = {}) {
      this.config = { ...defaultConfig, ...config }
      this.element = null
      this.isVisible = true
      this.isDragging = false
      this.dragOffset = { x: 0, y: 0 }
      this.chatModal = null
      this.badgeCount = 0
      this.autoHideTimer = null
      this.instanceId = Date.now() + '-' + Math.random().toString(36).substr(2, 9)

      // 新增：模态窗口拖拽和最大化状态
      this.isModalDragging = false
      this.modalDragOffset = { x: 0, y: 0 }
      this.isModalMaximized = false
      this.modalOriginalState = { width: 0, height: 0, left: 0, top: 0, right: 0, bottom: 0 }

      // 新增：模态窗口大小调整状态
      this.isModalResizing = false
      this.resizeDirection = null
      this.resizeStartState = null
      this.minModalWidth = 400
      this.minModalHeight = 300
      this.maxModalWidth = window.innerWidth - 100
      this.maxModalHeight = window.innerHeight - 100

      // 验证必需参数
      if (!this.config.token) {
        throw new Error('Token is required for AI Assistant Widget')
      }

      this.init()
    }

    /**
     * 初始化组件
     */
    init() {
      this.createElement()
      this.addStyles()
      this.bindEvents()
      this.setPosition()

      // 触发就绪回调
      if (this.config.onReady && typeof this.config.onReady === 'function') {
        this.config.onReady(this)
      }
    }

    /**
     * 创建DOM元素 - 简洁结构
     */
    createElement() {
      this.element = document.createElement('div')
      this.element.className = 'ai-assistant-v2'
      this.element.innerHTML = `
        <div class="ai-ripple-container">
          <div class="ai-ripple"></div>
          <div class="ai-ripple ai-ripple-delay-1"></div>
          <div class="ai-ripple ai-ripple-delay-2"></div>
        </div>
        <div class="ai-button" role="button" aria-label="${this.config.tooltip}">
          <div class="ai-icon">${this.getIconHTML()}</div>
          <div class="ai-badge" style="display: none;">
            <span class="badge-count">0</span>
          </div>
        </div>
        <div class="ai-tooltip">${this.config.tooltip}</div>
      `

      document.body.appendChild(this.element)
    }

    /**
     * 获取图标HTML
     */
    getIconHTML() {
      const icons = {
        robot: `
          <div class="robot-head">
            <div class="robot-eyes">
              <div class="eye"></div>
              <div class="eye"></div>
            </div>
            <div class="robot-mouth"></div>
          </div>
        `,
        chat: `
          <div class="chat-icon">
            <div class="chat-bubble">
              <div class="chat-dots">
                <div class="dot"></div>
                <div class="dot"></div>
                <div class="dot"></div>
              </div>
            </div>
          </div>
        `,
        ai: `
          <div class="ai-text">
            <span>AI</span>
          </div>
        `,
        brain: `
          <div class="brain-icon">
            <div class="brain-left"></div>
            <div class="brain-right"></div>
            <div class="brain-line"></div>
          </div>
        `,
      }
      return icons[this.config.iconType] || icons.robot
    }

    /**
     * 添加CSS样式
     */
    addStyles() {
      if (document.getElementById('ai-assistant-v2-styles')) {
        return
      }

      const styles = document.createElement('style')
      styles.id = 'ai-assistant-v2-styles'
      styles.textContent = `
        .ai-assistant-v2 {
          position: fixed;
          z-index: 999999;
          font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
          user-select: none;
          transition: all 0.3s ease;
        }

        /* 波纹容器 */
        .ai-ripple-container {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          width: ${this.config.size}px;
          height: ${this.config.size}px;
          pointer-events: none;
        }

        /* 波纹效果 */
        .ai-ripple {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          border: 2px solid ${this.config.primaryColor};
          border-radius: 50%;
          opacity: 0;
          animation: ripple-effect 3s infinite;
        }

        .ai-ripple-delay-1 {
          animation-delay: 1s;
        }

        .ai-ripple-delay-2 {
          animation-delay: 2s;
        }

                 @keyframes ripple-effect {
           0% {
             transform: scale(1);
             opacity: 0.6;
           }
           50% {
             opacity: 0.3;
           }
           100% {
             transform: scale(1.8);
             opacity: 0;
           }
         }

        .ai-button {
          position: relative;
          width: ${this.config.size}px;
          height: ${this.config.size}px;
          ${this.getThemeStyles()}
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
          box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15), 0 2px 8px rgba(0, 0, 0, 0.1);
          border: 2px solid rgba(255, 255, 255, 0.2);
          backdrop-filter: blur(10px);
          z-index: 1;
        }

        .ai-button:hover {
          transform: scale(1.1) rotate(5deg);
          box-shadow: 0 8px 30px rgba(0, 0, 0, 0.2), 0 4px 15px ${this.config.primaryColor}40;
          border-color: rgba(255, 255, 255, 0.4);
        }

        .ai-button:active {
          transform: scale(0.95);
          transition: all 0.1s ease;
        }

        .ai-icon {
          color: white;
          font-size: ${this.config.size * 0.4}px;
          font-weight: bold;
          display: flex;
          align-items: center;
          justify-content: center;
          width: 100%;
          height: 100%;
        }

        /* 机器人图标样式 */
        .robot-head {
          width: 28px;
          position: relative;
        }

        .robot-eyes {
          display: flex;
          justify-content: space-between;
          margin-bottom: 4px;
          padding: 0 4px;
        }

        .eye {
          width: 6px;
          height: 6px;
          background: white;
          border-radius: 50%;
          animation: blink 3s infinite;
        }

        .robot-mouth {
          width: 12px;
          height: 2px;
          background: white;
          border-radius: 1px;
          margin: 0 auto;
          opacity: 0.8;
        }

        @keyframes blink {
          0%, 90%, 100% { transform: scaleY(1); }
          95% { transform: scaleY(0.1); }
        }

        /* 对话图标样式 */
        .chat-icon {
          width: 28px;
          height: 28px;
          position: relative;
        }

        .chat-bubble {
          width: 24px;
          height: 18px;
          background: white;
          border-radius: 12px 12px 12px 4px;
          position: relative;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .chat-dots {
          display: flex;
          gap: 2px;
        }

        .dot {
          width: 3px;
          height: 3px;
          background: ${this.config.primaryColor};
          border-radius: 50%;
          animation: typing 1.5s infinite;
        }

        .dot:nth-child(2) { animation-delay: 0.2s; }
        .dot:nth-child(3) { animation-delay: 0.4s; }

        @keyframes typing {
          0%, 60%, 100% { transform: translateY(0); opacity: 1; }
          30% { transform: translateY(-8px); opacity: 0.7; }
        }

        /* AI文字样式 */
        .ai-text {
          font-size: 18px;
          font-weight: 700;
          color: white;
          text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
          letter-spacing: 1px;
        }

        /* 大脑图标样式 */
        .brain-icon {
          width: 28px;
          height: 28px;
          position: relative;
        }

        .brain-left, .brain-right {
          width: 12px;
          height: 16px;
          background: white;
          border-radius: 12px 6px 6px 12px;
          position: absolute;
          opacity: 0.9;
        }

        .brain-left {
          left: 2px;
          transform: rotate(-10deg);
        }

        .brain-right {
          right: 2px;
          transform: rotate(10deg) scaleX(-1);
        }

        .brain-line {
          position: absolute;
          top: 50%;
          left: 50%;
          width: 2px;
          height: 12px;
          background: white;
          transform: translate(-50%, -50%);
          opacity: 0.6;
        }

        /* 徽章样式 */
        .ai-badge {
          position: absolute;
          top: -6px;
          right: -6px;
          background: linear-gradient(135deg, #ff6b6b, #ee5a52);
          color: white;
          border-radius: 50%;
          min-width: 20px;
          height: 20px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 11px;
          font-weight: bold;
          border: 2px solid white;
          box-shadow: 0 2px 8px rgba(255, 107, 107, 0.4);
          animation: pulse-badge 2s infinite;
        }

        @keyframes pulse-badge {
          0%, 100% { transform: scale(1); }
          50% { transform: scale(1.1); }
        }

        /* 工具提示 */
        .ai-tooltip {
          position: absolute;
          background: rgba(0, 0, 0, 0.8);
          color: white;
          padding: 8px 12px;
          border-radius: 6px;
          font-size: 13px;
          white-space: nowrap;
          opacity: 0;
          pointer-events: none;
          transition: opacity 0.3s ease;
          transform: translateX(-50%);
          bottom: ${this.config.size + 12}px;
          left: 50%;
          backdrop-filter: blur(10px);
        }

        .ai-tooltip::after {
          content: '';
          position: absolute;
          top: 100%;
          left: 50%;
          transform: translateX(-50%);
          border: 5px solid transparent;
          border-top-color: rgba(0, 0, 0, 0.8);
        }

        .ai-assistant-v2:hover .ai-tooltip {
          opacity: 1;
        }

        .ai-assistant-v2.dragging {
          transform: scale(1.05);
        }

        .ai-assistant-v2.dragging .ai-tooltip {
          opacity: 0;
        }

        .ai-assistant-v2.hidden {
          opacity: 0;
          pointer-events: none;
          transform: scale(0.8);
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
          .ai-assistant-v2 {
            transform: scale(0.9);
          }

          .ai-tooltip {
            font-size: 12px;
            padding: 6px 10px;
          }
        }

        /* 深色模式适配 */
        @media (prefers-color-scheme: dark) {
          .ai-button {
            border-color: rgba(255, 255, 255, 0.15);
          }
        }

        /* 动画优化 */
        @media (prefers-reduced-motion: reduce) {
          .ai-button, .ai-icon, .ai-tooltip {
            transition: none;
          }

          .eye, .dot, .ai-ripple {
            animation: none;
          }

          .ai-ripple {
            display: none;
          }
        }
      `

      document.head.appendChild(styles)
    }

    /**
     * 获取主题样式
     */
    getThemeStyles() {
      const themes = {
        gradient: `background: linear-gradient(135deg, ${this.config.primaryColor}, ${this.config.secondaryColor});`,
        solid: `background: ${this.config.primaryColor};`,
        outline: `background: rgba(255, 255, 255, 0.1); border: 3px solid ${this.config.primaryColor};`,
      }
      return themes[this.config.theme] || themes.gradient
    }

    /**
     * 绑定事件
     */
    bindEvents() {
      const button = this.element.querySelector('.ai-button')

      // 点击事件
      button.addEventListener('click', (e) => {
        e.preventDefault()
        e.stopPropagation()
        if (!this.isDragging) {
          this.openChat()
        }
      })

      // 拖拽事件
      if (this.config.draggable) {
        // 鼠标事件
        button.addEventListener('mousedown', this.handleMouseDown.bind(this))
        document.addEventListener('mousemove', this.handleMouseMove.bind(this))
        document.addEventListener('mouseup', this.handleMouseUp.bind(this))

        // 触摸事件
        button.addEventListener('touchstart', this.handleTouchStart.bind(this), { passive: false })
        document.addEventListener('touchmove', this.handleTouchMove.bind(this), { passive: false })
        document.addEventListener('touchend', this.handleTouchEnd.bind(this))
      }

      // 页面关闭时关闭聊天模态窗口
      window.addEventListener('beforeunload', () => {
        if (this.chatModal && !this.chatModal.classList.contains('ai-modal-hidden')) {
          this.closeChatModal()
        }
      })

      // 页面隐藏时不再自动关闭聊天模态窗口，保持用户会话状态
      // 注释掉原有的自动关闭逻辑，避免切换标签页时丢失对话
      // document.addEventListener('visibilitychange', () => {
      //   if (
      //     document.visibilityState === 'hidden' &&
      //     this.chatModal &&
      //     !this.chatModal.classList.contains('ai-modal-hidden')
      //   ) {
      //     this.closeChatModal()
      //   }
      // })
    }

    /**
     * 设置位置
     */
    setPosition() {
      const positions = {
        'bottom-right': { bottom: this.config.offset.y + 'px', right: this.config.offset.x + 'px' },
        'bottom-left': { bottom: this.config.offset.y + 'px', left: this.config.offset.x + 'px' },
        'top-right': { top: this.config.offset.y + 'px', right: this.config.offset.x + 'px' },
        'top-left': { top: this.config.offset.y + 'px', left: this.config.offset.x + 'px' },
      }

      const pos = positions[this.config.position] || positions['bottom-right']
      Object.assign(this.element.style, pos)
    }

    /**
     * 鼠标按下
     */
    handleMouseDown(e) {
      this.startDrag(e.clientX, e.clientY)
    }

    /**
     * 鼠标移动
     */
    handleMouseMove(e) {
      if (this.isDragging) {
        this.updateDrag(e.clientX, e.clientY)
      }
    }

    /**
     * 鼠标释放
     */
    handleMouseUp() {
      this.endDrag()
    }

    /**
     * 触摸开始
     */
    handleTouchStart(e) {
      e.preventDefault()
      const touch = e.touches[0]
      this.startDrag(touch.clientX, touch.clientY)
    }

    /**
     * 触摸移动
     */
    handleTouchMove(e) {
      e.preventDefault()
      if (this.isDragging && e.touches.length > 0) {
        const touch = e.touches[0]
        this.updateDrag(touch.clientX, touch.clientY)
      }
    }

    /**
     * 触摸结束
     */
    handleTouchEnd() {
      this.endDrag()
    }

    /**
     * 开始拖拽
     */
    startDrag(clientX, clientY) {
      const rect = this.element.getBoundingClientRect()
      this.dragOffset = {
        x: clientX - rect.left,
        y: clientY - rect.top,
      }
      this.isDragging = true
      this.element.classList.add('dragging')
    }

    /**
     * 更新拖拽位置
     */
    updateDrag(clientX, clientY) {
      if (!this.isDragging) return

      const x = clientX - this.dragOffset.x
      const y = clientY - this.dragOffset.y

      // 边界限制
      const maxX = window.innerWidth - this.config.size
      const maxY = window.innerHeight - this.config.size

      const finalX = Math.max(0, Math.min(x, maxX))
      const finalY = Math.max(0, Math.min(y, maxY))

      this.element.style.left = finalX + 'px'
      this.element.style.top = finalY + 'px'
      this.element.style.right = 'auto'
      this.element.style.bottom = 'auto'
    }

    /**
     * 结束拖拽
     */
    endDrag() {
      if (this.isDragging) {
        this.isDragging = false
        this.element.classList.remove('dragging')

        // 延迟一点时间，避免拖拽结束立即触发点击
        setTimeout(() => {
          this.isDragging = false
        }, 100)
      }
    }

    /**
     * 开始模态窗口拖拽
     */
    startModalDrag(e) {
      if (this.isModalMaximized) {
        return // 最大化状态下不允许拖拽
      }

      const container = this.chatModal.querySelector('.ai-modal-container')
      const rect = container.getBoundingClientRect()

      this.modalDragOffset = {
        x: e.clientX - rect.left,
        y: e.clientY - rect.top
      }

      this.isModalDragging = true
      container.classList.add('dragging')
      e.preventDefault()
    }

    /**
     * 更新模态窗口拖拽位置
     */
    updateModalDrag(e) {
      if (!this.isModalDragging || this.isModalMaximized) return

      const container = this.chatModal.querySelector('.ai-modal-container')
      const x = e.clientX - this.modalDragOffset.x
      const y = e.clientY - this.modalDragOffset.y

      // 边界限制
      const maxX = window.innerWidth - container.offsetWidth
      const maxY = window.innerHeight - container.offsetHeight

      const finalX = Math.max(0, Math.min(x, maxX))
      const finalY = Math.max(0, Math.min(y, maxY))

      container.style.left = finalX + 'px'
      container.style.top = finalY + 'px'
      container.style.right = 'auto'
      container.style.bottom = 'auto'
    }

    /**
     * 结束模态窗口拖拽
     */
    endModalDrag() {
      if (this.isModalDragging) {
        this.isModalDragging = false
        const container = this.chatModal.querySelector('.ai-modal-container')
        container.classList.remove('dragging')
      }
    }

    /**
     * 开始模态窗口大小调整
     */
        startModalResize(e, direction) {
      if (this.isModalMaximized) {
        return // 最大化状态下不允许调整大小
      }

      const container = this.chatModal.querySelector('.ai-modal-container')
      const rect = container.getBoundingClientRect()

      this.resizeDirection = direction
      this.isModalResizing = true
      this.resizeStartState = {
        x: e.clientX,
        y: e.clientY,
        width: rect.width,
        height: rect.height,
        left: rect.left,
        top: rect.top
      }

      container.classList.add('resizing')
      document.body.style.cursor = getComputedStyle(e.target).cursor
      e.preventDefault()
      e.stopPropagation()
    }

    /**
     * 更新模态窗口大小调整
     */
    updateModalResize(e) {
      if (!this.isModalResizing || this.isModalMaximized) return

      const container = this.chatModal.querySelector('.ai-modal-container')
      const deltaX = e.clientX - this.resizeStartState.x
      const deltaY = e.clientY - this.resizeStartState.y

      let newWidth = this.resizeStartState.width
      let newHeight = this.resizeStartState.height
      let newLeft = this.resizeStartState.left
      let newTop = this.resizeStartState.top

      // 根据拖拽方向计算新尺寸和位置
      switch (this.resizeDirection) {
        case 'right':
          newWidth = this.resizeStartState.width + deltaX
          break
        case 'left':
          newWidth = this.resizeStartState.width - deltaX
          newLeft = this.resizeStartState.left + deltaX
          break
        case 'bottom':
          newHeight = this.resizeStartState.height + deltaY
          break
        case 'top':
          newHeight = this.resizeStartState.height - deltaY
          newTop = this.resizeStartState.top + deltaY
          break
        case 'bottom-right':
          newWidth = this.resizeStartState.width + deltaX
          newHeight = this.resizeStartState.height + deltaY
          break
        case 'bottom-left':
          newWidth = this.resizeStartState.width - deltaX
          newHeight = this.resizeStartState.height + deltaY
          newLeft = this.resizeStartState.left + deltaX
          break
        case 'top-right':
          newWidth = this.resizeStartState.width + deltaX
          newHeight = this.resizeStartState.height - deltaY
          newTop = this.resizeStartState.top + deltaY
          break
        case 'top-left':
          newWidth = this.resizeStartState.width - deltaX
          newHeight = this.resizeStartState.height - deltaY
          newLeft = this.resizeStartState.left + deltaX
          newTop = this.resizeStartState.top + deltaY
          break
      }

      // 应用尺寸限制，同时调整位置
      const constrainedWidth = Math.max(this.minModalWidth, Math.min(newWidth, this.maxModalWidth))
      const constrainedHeight = Math.max(this.minModalHeight, Math.min(newHeight, this.maxModalHeight))

      // 如果宽度被限制，调整左侧位置
      if (this.resizeDirection.includes('left') && constrainedWidth !== newWidth) {
        newLeft = this.resizeStartState.left - (constrainedWidth - this.resizeStartState.width)
      }

      // 如果高度被限制，调整顶部位置
      if (this.resizeDirection.includes('top') && constrainedHeight !== newHeight) {
        newTop = this.resizeStartState.top - (constrainedHeight - this.resizeStartState.height)
      }

      newWidth = constrainedWidth
      newHeight = constrainedHeight

      // 边界检查
      newLeft = Math.max(0, Math.min(newLeft, window.innerWidth - newWidth))
      newTop = Math.max(0, Math.min(newTop, window.innerHeight - newHeight))

      // 应用新的尺寸和位置
      container.style.width = newWidth + 'px'
      container.style.height = newHeight + 'px'
      container.style.left = newLeft + 'px'
      container.style.top = newTop + 'px'
      container.style.right = 'auto'
      container.style.bottom = 'auto'
    }

    /**
     * 结束模态窗口大小调整
     */
    endModalResize() {
      if (this.isModalResizing) {
        this.isModalResizing = false
        this.resizeDirection = null
        this.resizeStartState = null
        const container = this.chatModal.querySelector('.ai-modal-container')
        container.classList.remove('resizing')
        document.body.style.cursor = ''
      }
    }

    /**
     * 切换模态窗口最大化状态
     */
    toggleModalMaximize() {
      const container = this.chatModal.querySelector('.ai-modal-container')
      const maximizeBtn = this.chatModal.querySelector('.ai-modal-maximize')

      if (this.isModalMaximized) {
        // 还原
        this.restoreModal(container)
        this.isModalMaximized = false

        // 更新按钮图标为最大化
        maximizeBtn.innerHTML = `
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
            <rect x="9" y="9" width="6" height="6"></rect>
          </svg>
        `
      } else {
        // 最大化
        this.maximizeModal(container)
        this.isModalMaximized = true

        // 更新按钮图标为还原
        maximizeBtn.innerHTML = `
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <rect x="3" y="3" width="10" height="10" rx="1" ry="1"></rect>
            <rect x="11" y="11" width="10" height="10" rx="1" ry="1"></rect>
          </svg>
        `
      }
    }

    /**
     * 最大化模态窗口
     */
    maximizeModal(container) {
      // 保存当前状态
      const styles = window.getComputedStyle(container)
      this.modalOriginalState = {
        width: container.offsetWidth,
        height: container.offsetHeight,
        left: styles.left,
        top: styles.top,
        right: styles.right,
        bottom: styles.bottom
      }

      // 设置最大化样式
      container.style.left = '0'
      container.style.top = '0'
      container.style.right = '0'
      container.style.bottom = '0'
      container.style.width = '100vw'
      container.style.height = '100vh'
      container.style.maxWidth = '100vw'
      container.style.maxHeight = '100vh'
      container.style.borderRadius = '0'

      container.classList.add('maximized')
    }

    /**
     * 还原模态窗口
     */
    restoreModal(container) {
      // 恢复原始样式
      container.style.left = this.modalOriginalState.left
      container.style.top = this.modalOriginalState.top
      container.style.right = this.modalOriginalState.right
      container.style.bottom = this.modalOriginalState.bottom
      container.style.width = this.modalOriginalState.width + 'px'
      container.style.height = this.modalOriginalState.height + 'px'
      container.style.maxWidth = 'calc(100vw - 48px)'
      container.style.maxHeight = 'calc(100vh - 140px)'
      container.style.borderRadius = '16px'

      container.classList.remove('maximized')
    }

    /**
     * 打开聊天窗口
     */
    openChat() {
      try {
        // 检查是否已有打开的模态窗口
        if (this.chatModal && !this.chatModal.classList.contains('ai-modal-hidden')) {
          this.focusModal()
          return
        }

        // 构建URL - 支持/chat/chat路径访问，带上token参数时不需要登录
        let url = `${this.config.baseUrl}/chat/chat?token=${encodeURIComponent(this.config.token)}`
        if (this.config.datasetId) {
          url += `&dataset_id=${encodeURIComponent(this.config.datasetId)}`
        }

        // 创建或显示模态窗口
        this.createChatModal(url)

        // 触发打开回调
        if (this.config.onOpen && typeof this.config.onOpen === 'function') {
          this.config.onOpen(this.chatModal)
        }
      } catch (error) {
        console.error('打开聊天窗口失败:', error)
        alert('无法打开聊天窗口，请稍后重试')
      }
    }

    /**
     * 创建聊天模态窗口
     */
    createChatModal(url) {
      if (this.chatModal) {
        const iframe = this.chatModal.querySelector('.ai-modal-iframe')
        iframe.src = url
        this.showModal()
        return
      }

      this.chatModal = document.createElement('div')
      this.chatModal.className = 'ai-chat-modal'
      this.chatModal.innerHTML = `
        <div class="ai-modal-container">
          <div class="ai-modal-header" style="cursor: move;">
            <div class="ai-modal-title">
              <div class="modal-icon">${this.getIconHTML()}</div>
              <span>DataTK AI智能助理</span>
            </div>
            <div class="ai-modal-controls">
              <button class="ai-modal-maximize" aria-label="最大化/还原">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
                  <rect x="9" y="9" width="6" height="6"></rect>
                </svg>
              </button>
              <button class="ai-modal-close" aria-label="关闭">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <line x1="18" y1="6" x2="6" y2="18"></line>
                  <line x1="6" y1="6" x2="18" y2="18"></line>
                </svg>
              </button>
            </div>
          </div>
          <div class="ai-modal-body">
            <iframe class="ai-modal-iframe" src="${url}" frameborder="0"></iframe>
          </div>
          <!-- 窗口大小调整手柄 -->
          <div class="ai-modal-resize-handles">
            <!-- 四个边的调整手柄 -->
            <div class="ai-modal-resize-handle ai-modal-resize-top" data-direction="top"></div>
            <div class="ai-modal-resize-handle ai-modal-resize-right" data-direction="right"></div>
            <div class="ai-modal-resize-handle ai-modal-resize-bottom" data-direction="bottom"></div>
            <div class="ai-modal-resize-handle ai-modal-resize-left" data-direction="left"></div>
            <!-- 四个角的调整手柄 -->
            <div class="ai-modal-resize-handle ai-modal-resize-corner ai-modal-resize-top-left" data-direction="top-left"></div>
            <div class="ai-modal-resize-handle ai-modal-resize-corner ai-modal-resize-top-right" data-direction="top-right"></div>
            <div class="ai-modal-resize-handle ai-modal-resize-corner ai-modal-resize-bottom-left" data-direction="bottom-left"></div>
            <div class="ai-modal-resize-handle ai-modal-resize-corner ai-modal-resize-bottom-right" data-direction="bottom-right"></div>
          </div>
        </div>
      `

      this.addModalStyles()
      document.body.appendChild(this.chatModal)
      this.bindModalEvents()
      this.showModal()
    }

    /**
     * 添加模态窗口样式
     */
    addModalStyles() {
      if (document.getElementById('ai-modal-v2-styles')) {
        return
      }

      const styles = document.createElement('style')
      styles.id = 'ai-modal-v2-styles'
      styles.textContent = `
        .ai-chat-modal {
          position: fixed;
          z-index: 999998;
          font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
          opacity: 0;
          transition: opacity 0.3s ease;
        }

        .ai-chat-modal.ai-modal-show {
          opacity: 1;
        }

        .ai-chat-modal.ai-modal-hidden {
          display: none;
        }

        .ai-modal-container {
          position: fixed;
          bottom: ${this.config.offset.y + this.config.size + 16}px;
          right: ${this.config.offset.x}px;
          width: ${this.config.modalWidth}px;
          height: ${this.config.modalHeight}px;
          max-width: calc(100vw - 48px);
          max-height: calc(100vh - 140px);
          border-radius: 16px;
          box-shadow: 0 25px 50px rgba(0, 0, 0, 0.25);
          display: flex;
          flex-direction: column;
          overflow: visible;
          transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
          transform: translateY(0);
          background: white;
        }

        .ai-chat-modal:not(.ai-modal-show) .ai-modal-container {
          transform: translateY(100%);
          opacity: 0;
        }

        .ai-modal-header {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 10px 24px;
          background: linear-gradient(135deg, ${this.config.primaryColor}, ${this.config.secondaryColor});
          color: white;
          user-select: none;
        }

        .ai-modal-header.dragging {
          cursor: grabbing !important;
        }

        .ai-modal-title {
          display: flex;
          align-items: center;
          gap: 12px;
          font-weight: 600;
          font-size: 18px;
          pointer-events: none;
        }

        .modal-icon {
          width: 32px;
          height: 32px;
          display: flex;
          align-items: center;
          justify-content: center;
          background: rgba(255, 255, 255, 0.2);
          border-radius: 50%;
          font-size: 14px;
        }

        .ai-modal-controls {
          display: flex;
          align-items: center;
          gap: 4px;
        }

        .ai-modal-maximize,
        .ai-modal-close {
          background: none;
          border: none;
          color: white;
          cursor: pointer;
          padding: 8px;
          border-radius: 6px;
          transition: background-color 0.2s ease;
          display: flex;
          align-items: center;
          justify-content: center;
          width: 36px;
          height: 36px;
        }

        .ai-modal-maximize:hover,
        .ai-modal-close:hover {
          background: rgba(255, 255, 255, 0.2);
        }

        .ai-modal-maximize:active,
        .ai-modal-close:active {
          background: rgba(255, 255, 255, 0.3);
        }

        .ai-modal-container.dragging {
          box-shadow: 0 35px 80px rgba(0, 0, 0, 0.35);
          transform: scale(1.02);
        }

        .ai-modal-container.maximized {
          box-shadow: none;
          border-radius: 0 !important;
        }

        .ai-modal-body {
          flex: 1;
          overflow: hidden;
          border-radius: 0 0 16px 16px;
        }

        .ai-modal-iframe {
          width: 100%;
          height: 100%;
          border: none;
          display: block;
        }

        /* 窗口大小调整手柄 - 全局样式 */
        .ai-modal-resize-handles {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          pointer-events: none;
        }

        .ai-modal-resize-handle {
          position: absolute;
          pointer-events: auto;
          background: rgba(255, 255, 255, 0.01);
          z-index: 10;
          transition: all 0.2s ease;
        }

        .ai-modal-resize-handle:hover {
          background: rgba(74, 144, 226, 0.3);
        }

        /* 调试模式：让resize handles更明显 */
        .ai-modal-container:hover .ai-modal-resize-handle {
          background: rgba(74, 144, 226, 0.1);
        }

        /* 边缘调整手柄 */
        .ai-modal-resize-top {
          top: -5px;
          left: 15px;
          right: 15px;
          height: 10px;
          cursor: n-resize;
        }

        .ai-modal-resize-bottom {
          bottom: -5px;
          left: 15px;
          right: 15px;
          height: 10px;
          cursor: s-resize;
        }

        .ai-modal-resize-left {
          left: -5px;
          top: 15px;
          bottom: 15px;
          width: 10px;
          cursor: w-resize;
        }

        .ai-modal-resize-right {
          right: -5px;
          top: 15px;
          bottom: 15px;
          width: 10px;
          cursor: e-resize;
        }

        /* 角落调整手柄 */
        .ai-modal-resize-corner {
          width: 15px;
          height: 15px;
        }

        .ai-modal-resize-top-left {
          top: -5px;
          left: -5px;
          cursor: nw-resize;
        }

        .ai-modal-resize-top-right {
          top: -5px;
          right: -5px;
          cursor: ne-resize;
        }

        .ai-modal-resize-bottom-left {
          bottom: -5px;
          left: -5px;
          cursor: sw-resize;
        }

        .ai-modal-resize-bottom-right {
          bottom: -5px;
          right: -5px;
          cursor: se-resize;
        }

        /* 最大化状态下隐藏调整手柄 */
        .ai-modal-container.maximized .ai-modal-resize-handles {
          display: none;
        }

        /* 调整时的视觉反馈 */
        .ai-modal-container.resizing {
          user-select: none;
          transition: none !important;
        }

        .ai-modal-container.resizing .ai-modal-iframe {
          pointer-events: none;
        }

        @media (max-width: 768px) {
          .ai-modal-container {
            width: calc(100vw - 24px);
            height: calc(100vh - 120px);
            right: 12px;
            bottom: ${this.config.offset.y}px;
            border-radius: 12px;
          }

          .ai-modal-header {
            padding: 10px 20px;
          }

          .ai-modal-title {
            font-size: 16px;
          }

          .ai-modal-maximize,
          .ai-modal-close {
            width: 32px;
            height: 32px;
            padding: 6px;
          }

          /* 移动端自动最大化 */
          .ai-modal-container.mobile-auto-maximize {
            width: 100vw !important;
            height: 100vh !important;
            left: 0 !important;
            top: 0 !important;
            right: 0 !important;
            bottom: 0 !important;
            border-radius: 0 !important;
            max-width: 100vw !important;
            max-height: 100vh !important;
          }

          /* 移动端禁用resize功能 */
          .ai-modal-resize-handles {
            display: none;
          }
        }
      `

      document.head.appendChild(styles)
    }

    /**
     * 绑定模态窗口事件
     */
    bindModalEvents() {
      const closeBtn = this.chatModal.querySelector('.ai-modal-close')
      const maximizeBtn = this.chatModal.querySelector('.ai-modal-maximize')
      const header = this.chatModal.querySelector('.ai-modal-header')

      // 关闭按钮事件
      closeBtn.addEventListener('click', () => {
        this.closeChatModal()
      })

      // 最大化按钮事件
      maximizeBtn.addEventListener('click', () => {
        this.toggleModalMaximize()
      })

      // 头部拖拽事件
      header.addEventListener('mousedown', (e) => {
        // 避免点击按钮时触发拖拽
        if (e.target.closest('.ai-modal-controls')) {
          return
        }
        this.startModalDrag(e)
      })

      // 绑定resize手柄事件
      const resizeHandles = this.chatModal.querySelectorAll('.ai-modal-resize-handle')
      resizeHandles.forEach(handle => {
        handle.addEventListener('mousedown', (e) => {
          const direction = handle.getAttribute('data-direction')
          this.startModalResize(e, direction)
        })
      })

      // 全局鼠标事件（用于拖拽和resize）
      const handleMouseMove = (e) => {
        if (this.isModalDragging) {
          this.updateModalDrag(e)
        } else if (this.isModalResizing) {
          this.updateModalResize(e)
        }
      }

      const handleMouseUp = () => {
        this.endModalDrag()
        this.endModalResize()
      }

      document.addEventListener('mousemove', handleMouseMove)
      document.addEventListener('mouseup', handleMouseUp)

      // ESC键关闭
      const handleEsc = (e) => {
        if (e.key === 'Escape' && !this.chatModal.classList.contains('ai-modal-hidden')) {
          this.closeChatModal()
        }
      }
      document.addEventListener('keydown', handleEsc)

      // 双击头部最大化
      header.addEventListener('dblclick', (e) => {
        if (!e.target.closest('.ai-modal-controls')) {
          this.toggleModalMaximize()
        }
      })

      this.modalCleanup = () => {
        document.removeEventListener('keydown', handleEsc)
        document.removeEventListener('mousemove', handleMouseMove)
        document.removeEventListener('mouseup', handleMouseUp)
      }
    }

    /**
     * 显示模态窗口
     */
    showModal() {
      this.chatModal.classList.remove('ai-modal-hidden')
      requestAnimationFrame(() => {
        this.chatModal.classList.add('ai-modal-show')
      })

      this.hideBadge()
    }

    /**
     * 聚焦模态窗口
     */
    focusModal() {
      if (this.chatModal) {
        const iframe = this.chatModal.querySelector('.ai-modal-iframe')
        if (iframe) {
          iframe.focus()
        }
      }
    }

    /**
     * 关闭聊天模态窗口
     */
    closeChatModal() {
      if (!this.chatModal) return

      // 重置拖拽、最大化和resize状态
      this.isModalDragging = false
      this.isModalMaximized = false
      this.isModalResizing = false
      this.resizeDirection = null
      this.resizeStartState = null

      this.chatModal.classList.remove('ai-modal-show')

      setTimeout(() => {
        if (this.chatModal) {
          this.chatModal.classList.add('ai-modal-hidden')
          // 重置容器样式
          const container = this.chatModal.querySelector('.ai-modal-container')
          if (container) {
            container.classList.remove('dragging', 'maximized', 'resizing')
          }
        }
      }, 300)

      if (this.config.onClose && typeof this.config.onClose === 'function') {
        this.config.onClose()
      }
    }

    /**
     * 显示徽章
     */
    showBadge(count = 1) {
      this.badgeCount = count
      const badge = this.element.querySelector('.ai-badge')
      const badgeCount = this.element.querySelector('.badge-count')

      if (badge && badgeCount) {
        badgeCount.textContent = count > 99 ? '99+' : count
        badge.style.display = 'flex'
      }
    }

    /**
     * 隐藏徽章
     */
    hideBadge() {
      this.badgeCount = 0
      const badge = this.element.querySelector('.ai-badge')
      if (badge) {
        badge.style.display = 'none'
      }
    }

    /**
     * 显示助理
     */
    show() {
      this.isVisible = true
      this.element.classList.remove('hidden')
    }

    /**
     * 隐藏助理
     */
    hide() {
      this.isVisible = false
      this.element.classList.add('hidden')
    }

    /**
     * 切换显示状态
     */
    toggle() {
      if (this.isVisible) {
        this.hide()
      } else {
        this.show()
      }
    }

    /**
     * 更新配置
     */
    updateConfig(newConfig) {
      this.config = { ...this.config, ...newConfig }

      // 重新创建元素
      if (this.element && this.element.parentNode) {
        this.element.parentNode.removeChild(this.element)
      }

      // 移除旧样式
      const oldStyles = document.getElementById('ai-assistant-v2-styles')
      if (oldStyles) {
        oldStyles.remove()
      }

      // 重新初始化
      this.createElement()
      this.addStyles()
      this.bindEvents()
      this.setPosition()
    }

    /**
     * 销毁组件
     */
    destroy() {
      if (this.chatModal) {
        this.closeChatModal()
        if (this.modalCleanup) {
          this.modalCleanup()
        }
        if (this.chatModal.parentNode) {
          this.chatModal.parentNode.removeChild(this.chatModal)
        }
      }

      if (this.element && this.element.parentNode) {
        this.element.parentNode.removeChild(this.element)
      }

      this.element = null
      this.chatModal = null
    }
  }

  /**
   * 全局API
   */
  const AIAssistant = {
    version: '2.0.0',
    instance: null,

    init(config) {
      if (this.instance) {
        console.warn('AI Assistant already initialized')
        return this.instance
      }
      this.instance = new AIAssistantWidget(config)
      return this.instance
    },

    getInstance() {
      return this.instance
    },

    destroy() {
      if (this.instance) {
        this.instance.destroy()
        this.instance = null
      }
    },

    create(config) {
      return new AIAssistantWidget(config)
    },
  }

  // 导出到全局
  global.AIAssistant = AIAssistant

  // AMD支持
  if (typeof global.define === 'function' && global.define.amd) {
    global.define(function () {
      return AIAssistant
    })
  }

  // CommonJS支持
  if (typeof global.module !== 'undefined' && global.module.exports) {
    global.module.exports = AIAssistant
  }
})(typeof window !== 'undefined' ? window : this)

/* 使用示例:

// 1. 基本初始化 - 机器人图标
AIAssistant.init({
  token: 'your_token_here',
  datasetId: 'dataset_id_here'
});

// 2. 对话气泡风格
AIAssistant.init({
  token: 'your_token_here',
  iconType: 'chat',
  theme: 'gradient',
  primaryColor: '#10B981',
  secondaryColor: '#059669'
});

// 3. AI文字风格
AIAssistant.init({
  token: 'your_token_here',
  iconType: 'ai',
  theme: 'solid',
  primaryColor: '#8B5CF6',
  size: 72
});

// 4. 大脑图标 + 轮廓主题
AIAssistant.init({
  token: 'your_token_here',
  iconType: 'brain',
  theme: 'outline',
  primaryColor: '#F59E0B',
  size: 56
});

// 5. 自定义聊天窗口尺寸
AIAssistant.init({
  token: 'your_token_here',
  modalWidth: 800,
  modalHeight: 600,
  offset: { x: 30, y: 30 }
});

// 6. 完整配置示例
AIAssistant.init({
  token: 'your_token_here',
  datasetId: 'dataset_id_here',
  iconType: 'robot',
  theme: 'gradient',
  primaryColor: '#667eea',
  secondaryColor: '#764ba2',
  size: 64,
  offset: { x: 40, y: 40 },
  modalWidth: 1100,
  modalHeight: 800
});

*/
